<template>
  <div id="addArticleView">
    <!--编辑文章头部区域-->
    <div id="articleHeader">
      <a-input
        placeholder="输入文章标题..."
        size="large"
        :max-length="50"
        allow-clear
        show-word-limit
        v-model="form.title"
      />
      <a-button
        type="primary"
        class="publicBtn"
        @click="publicArticle"
        :loading="loadStatus"
      >
        发布
      </a-button>
    </div>
    <!--编辑文章主题区域-->
    <div id="articleBody">
      <MdEditor
        :value="form.content"
        :handle-change="onContentChange"
        :upload-images="uploadImages"
      />
    </div>
    <!--文章封面区域-->
    <div id="articleCover">
      <a-upload
        draggable
        :limit="1"
        list-type="picture"
        @before-upload="beforeUpload"
        tip="文章封面"
        :show-cancel-button="false"
        @change="onChange"
        :custom-request="customUpload"
        :fileList="form.imageSrc ? [{ url: form.imageSrc }] : []"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { FileItem, Message } from "@arco-design/web-vue";
import axios from "axios";
import { ArticleControllerService } from "../../../generated";
import { useRoute, useRouter } from "vue-router";
import { baseUrl } from "@/plugins/axios";

const route = useRoute();
const router = useRouter();

// 点击链接加载状态
const loadStatus = ref(false);

// 提交的表单数据
let form = ref({
  title: "",
  content: "",
  imageSrc: "",
});

// 判断是新增还是更新
const updateFlag = route.path.includes("update");
/**
 * 根据文章id，加载数据
 */
const loadData = async () => {
  // 新增文章，直接返回
  if (!updateFlag) return;
  // 更新文章
  const articleId = route.query.id;
  if (!articleId) {
    Message.error("未获取到文章id");
    await router.push("/article/manage");
    return;
  }
  const res = await ArticleControllerService.getArticleByIdUsingGet(
    articleId as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
  } else {
    Message.error("糟糕，没找到你要的文章，" + res.message);
  }
};

/**
 * 组件渲染成功，调用加载数据函数
 */
onMounted(() => {
  loadData();
});

/**
 * 在文章内容改变时触发
 * @param value 新的文章内容
 */
const onContentChange = (value: string) => {
  form.value.content = value;
};

// 上传文章封面图片文件
const file = ref();

/**
 * 上传图片之前触发
 * @param file 图片文件
 */
const beforeUpload = (file: any) => {
  const isJpgOrPng =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/gif" ||
    file.type === "image/jpg";
  if (!isJpgOrPng) {
    Message.error("请上传正确的图片格式");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    Message.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};

/**
 * 上传文件状态发生改变时触发
 * @param _
 * @param currentFile 当前文件
 */
const onChange = async (_: never, currentFile: FileItem) => {
  file.value = {
    ...currentFile,
  };
};

/**
 * md上传图片
 * @param file 图片文件
 */
const uploadImages = async (file: any) => {
  const formData = new FormData();
  formData.append("file", file[0]);

  const res = await axios.post(baseUrl + "/api/file/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
  if (res.data.code === 0) {
    return [{ url: res.data.data }];
  } else {
    Message.error("上传图片失败，" + res.data.message);
    return [{ url: "" }];
  }
};

/**
 * 发布文章
 */
const publicArticle = async () => {
  // 校验form表单中的数据是否为空
  if (form.value.title === "") {
    Message.error("文章标题不能为空");
    return;
  }
  if (form.value.content === "") {
    Message.error("文章内容不能为空");
    return;
  }
  // 判断是更新还是新增
  loadStatus.value = true;
  let res;
  if (updateFlag) {
    // 更新
    res = await ArticleControllerService.updateArticleUsingPost(form.value);
  } else {
    // 新增
    res = await ArticleControllerService.addArticleUsingPost(form.value);
  }

  if (res.code === 0) {
    Message.success("发布成功");
  } else {
    Message.error("发布失败，" + JSON.stringify(res.data));
  }
  loadStatus.value = false;
};

/**
 * 上传文章封面图
 */
const customUpload = async () => {
  const formData = new FormData();
  formData.append("file", file.value.file);
  const res = await axios.post(baseUrl + "/api/file/upload", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });

  if (res.data != null) {
    Message.success("上传成功");
    form.value!.imageSrc = res.data.data;
  } else {
    Message.error("上传失败，" + JSON.stringify(res.data));
  }
};
</script>

<style scoped>
/*文章头部盒子*/
#articleHeader {
  display: flex;
}

/*标题输入框样式（覆盖原有组件库样式）*/
:deep(.arco-input-wrapper .arco-input.arco-input-size-large) {
  height: 35px;
  font-weight: 500;
  font-size: 24px;
  color: #1d2129;
  border: none;
  outline: none;
}

/*发布按钮*/
.publicBtn {
  height: 50px;
  width: 60px;
  margin-left: 10px;
  justify-content: flex-end;
}

/*md编辑器盒子*/
#articleBody {
  margin-top: 15px;
}

/*md编辑器*/
:deep(.bytemd) {
  height: 45vh;
}

/*上传文章封面盒子*/
#articleCover {
  margin-top: 15px;
}
</style>
